﻿using System;
using System.Collections.Generic;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.DataModel;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	public class InterchangeDuctWH : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			if (commandData == null)
			{
				throw new System.ArgumentNullException();
			}
			Document document = commandData.Application.ActiveUIDocument.Document;
			Selection selection = commandData.Application.ActiveUIDocument.Selection;
			List<ViewType> viewTypes = YJKRevitTools.ListViewNeed(2);
			if (!YJKRevitTools.ViewCheck(commandData.Application.ActiveUIDocument, viewTypes))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Result result;
			try
			{
				for (;;)
				{
					transaction = new Transaction(document, "互换风管宽高");
					transaction.Start();
					RevitVersionFuncs.ClearSelection(selection);
					DuctFilter ductFilter = new DuctFilter();
					Reference reference = selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, ductFilter, "请选择要互换宽高的风管：");
					Duct duct = document.GetElement(reference) as Duct;
					if (duct == null)
					{
						break;
					}
					RevitVersionFuncs.AddToSelection(selection, duct);
					new HYTagOperate().WHExchange(duct);
					document.Regenerate();
					transaction.Commit();
				}
				YJKMessageBox.Show("没有选中风管！");
				result = Autodesk.Revit.UI.Result.Failed;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
					if ((int)status == 1)
					{
						transaction.Commit();
					}
					else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
